<template>
  <a-card class="general-card" title="物流公司" :bordered="false">
    <tablePage
      ref="tablePageRef"
      :bordered="true"
      :columns="columnsTable"
      :methods="sortMethods"
      :api="getLogistics"
      :api-params="{ pageSize: 10000 }"
      :enable-pagination="false"
    >
      <template #selected="{ data }">
        <div
          v-if="
            (data.selected != '' && data.selected != null) ||
            data.selected != undefined
          "
        >
          <a-badge color="green" style="margin-right: 5px"></a-badge>开启
        </div>
        <div
          v-if="
            data.selected == '' ||
            data.selected == null ||
            data.selected == undefined
          "
        >
          <a-badge color="red" style="margin-right: 5px"></a-badge>关闭
        </div>
      </template>
      <template #open="{ data }"
        ><a-button
          v-if="!data.selected"
          type="text"
          status="success"
          @click="open(data)"
          >开启</a-button
        ></template
      >
      <template #close="{ data }"
        ><a-button
          v-if="data.selected"
          type="text"
          status="danger"
          @click="close(data)"
          >关闭</a-button
        ></template
      >
      <template #getFaceSheetInfo="{ data }"
        ><a-button
          v-if="data.selected"
          type="text"
          status="warning"
          @click="getFaceSheetInfo(data)"
          >修改</a-button
        ></template
      >
    </tablePage>

    <!--修改物流公司信息-->
    <a-modal
      v-model:visible="modalVisible"
      @ok="handleConfirm"
      @cancel="handleCancel"
    >
      <template #title>{{ openModalTitle }}</template>
      <a-form
        ref="formRef"
        :model="faceSheetForm"
        :style="{ width: '100%' }"
        layout="horizontal"
        auto-label-width
      >
        <a-form-item label="是否需要电子面单" field="faceSheetFlag">
          <a-radio-group v-model="faceSheetForm.faceSheetFlag" type="button">
            <a-radio :value="true" @click="faceSheetForm.faceSheetFlag = true"
              >需要</a-radio
            >
            <a-radio :value="false" @click="faceSheetForm.faceSheetFlag = false"
              >不需要</a-radio
            >
          </a-radio-group>
        </a-form-item>
        <a-card
          v-if="faceSheetForm.faceSheetFlag"
          hoverable
          :style="{ marginBottom: '20px' }"
        >
          <h4 style="color: #ff3c2a; margin: 0 0 10px">请输入详细信息</h4>
          <a-form-item label="customerName" field="customerName">
            <a-input v-model="faceSheetForm.customerName"></a-input>
          </a-form-item>
          <a-form-item label="customerPwd" field="customerPwd">
            <a-input v-model="faceSheetForm.customerPwd"></a-input>
          </a-form-item>
          <a-form-item label="monthCode" field="monthCode">
            <a-input v-model="faceSheetForm.monthCode"></a-input>
          </a-form-item>
          <a-form-item label="sendSite" field="sendSite">
            <a-input v-model="faceSheetForm.sendSite"></a-input>
          </a-form-item>
          <a-form-item label="sendStaff" field="sendStaff">
            <a-input v-model="faceSheetForm.sendStaff"></a-input>
          </a-form-item>
          <a-form-item label="支付方式" field="payType">
            <a-select v-model="faceSheetForm.payType">
              <a-option value="1">现付</a-option>
              <a-option value="2">到付</a-option>
              <a-option value="3">月结</a-option>
              <a-option value="4">第三方支付（仅SF支持）</a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="快递类型" field="expType">
            <a-input v-model="faceSheetForm.expType"></a-input>
          </a-form-item>
          <a-form-item>
            <a-button type="text" @click="frontDownload('use')"
              >使用说明</a-button
            >
            <a-button type="text" @click="frontDownload('type')"
              >快递类型</a-button
            >
          </a-form-item>
        </a-card>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script setup lang="ts">
  import tablePage from '@/components/table-pages/index.vue';
  import { MethodsRule, ColumnsDataRule } from '@/types/global';
  import {
    getLogistics,
    getIsCheck,
    logisticsChecked,
    logisticsUnChecked,
    editChecked,
  } from '@/api/logistics';
  import { ref } from 'vue';
  import useCurrentInstance from '@/hooks/useCurrentInstance';
  import { Message } from '@arco-design/web-vue';

  const modal = useCurrentInstance().globalProperties?.$modal; // 获取modal
  const modalVisible = ref(false); // modal显隐
  const logisticsId = ref('');
  const openModalTitle = ref('开启信息');
  const faceSheetForm = ref({
    faceSheetFlag: false,
    customerName: '',
    payType: '1',
    expType: '1',
    customerPwd: '',
    monthCode: '',
    sendSite: '',
    sendStaff: '',
  }) as any;
  const row = ref();
  // 搜索框初始化对象
  const searchForm = ref({
    pageNumber: 1, // 当前页数
    pageSize: 10, // 页面大小
    sort: 'createTime', // 默认排序字段
    order: 'desc', // 默认排序方式
  });
  const tablePageRef = ref<any>();
  const columnsTable: ColumnsDataRule[] = [
    { title: '物流公司', dataIndex: 'name', width: 300 },
    {
      title: '状态',
      dataIndex: 'selected',
      slot: true,
      slotTemplate: 'selected',
    },
  ];

  const sortMethods: MethodsRule = {
    title: '操作',
    width: 300,
    methods: [
      { title: '开启', callback: 'open', slot: true, slotTemplate: 'open' },
      { title: '关闭', callback: 'close', slot: true, slotTemplate: 'close' },
      {
        title: '修改',
        callback: 'getFaceSheetInfo',
        slot: true,
        slotTemplate: 'getFaceSheetInfo',
      },
    ],
  };
  // 开启
  const open = (v: any) => {
    row.value = v;
    logisticsId.value = v.logisticsId;
    modalVisible.value = true;
    openModalTitle.value = '开启信息';
  };
  // 关闭
  const close = (v: any) => {
    modal.confirm({
      title: '确认关闭',
      content: `您确认关闭此物流公司?`,
      alignCenter: false,
      onOk: async () => {
        const res = await logisticsUnChecked(v.logisticsId);
        if (res.data.success) {
          Message.success('物流公司关闭成功');
          tablePageRef.value.init();
        }
      },
    });
  };
  // 修改
  const getFaceSheetInfo = (v: any) => {
    row.value = v;
    modalVisible.value = true;
    logisticsId.value = v.logisticsId;
    openModalTitle.value = '修改信息';
    getIsCheck(logisticsId.value).then((res) => {
      if (res.data.success) {
        faceSheetForm.value = res.data.result;
      }
    });
  };
  // 表单修改确认
  const handleConfirm = () => {
    if (row.value.selected) {
      editChecked(logisticsId.value, faceSheetForm.value).then((res) => {
        if (res.data.success) {
          Message.success('修改成功！');
          tablePageRef.value.init();
        }
      });
    } else {
      logisticsChecked(logisticsId.value, faceSheetForm.value).then((res) => {
        if (res.data.success) {
          Message.success('物流公司开启成功！');
          tablePageRef.value.init();
        }
      });
    }
  };
  // 表单修改取消
  const handleCancel = (v: any) => {
    faceSheetForm.value.faceSheetFlag = false;
  };


  // 下载url(解决跨域a.download不生效问题)
  const downloadFile = (url: any, fileName: any) => {
    const x = new XMLHttpRequest();
    x.open("GET", url, true);
    x.responseType = 'blob';
    x.onload = function(e) {
      const url = window.URL.createObjectURL(x.response);
      const a = document.createElement('a');
      a.href = url;
      a.target = '_blank';
      a.download = fileName;
      a.click();
      a.remove();
    };
    x.send()
  };
  // 使用说明/快递类型excel下载
  const frontDownload = (val: any) => {
    const a = document.createElement('a'); // 创建一个<a></a>标签
    // 根据点击按钮来下载不同文件
    if (val === 'use') {
      a.href = "https://service.pickmall.cn:19000/micro/instructions.xlsx"; // 给a标签的href属性值加上地址，注意，这里是绝对路径，不用加 点.
      a.download = "使用说明.xlsx"; // 设置下载文件文件名，这里加上.xlsx指定文件类型，pdf文件就指定.fpd即可
    } else if (val === 'type') {
      a.href = "https://service.pickmall.cn:19000/micro/logisticsType.xlsx"; // 给a标签的href属性值加上地址，注意，这里是绝对路径，不用加 点.
      a.download = "快递类型.xlsx"; // 设置下载文件文件名，这里加上.xlsx指定文件类型，pdf文件就指定.fpd即可
    }
    downloadFile(a.href, a.download);
    // a.style.display = 'none'; // 障眼法藏起来a标签
    // document.body.appendChild(a); // 将a标签追加到文档对象中
    // console.log('a', a);
    // a.click(); // 模拟点击了a标签，会触发a标签的href的读取，浏览器就会自动下载了
    // a.remove(); // 一次性的，用完就删除a标签
  };
</script>
